package ar.com.nexttome.tasks;

import java.lang.ref.WeakReference;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.widget.ImageView;
import ar.com.nexttome.MainActivity;
import ar.com.nexttome.context.ApplicationContext;
import ar.com.nexttome.entities.Persona;
import ar.com.nexttome.util.HTTPClient;
import ar.com.nexttome.util.Tools;

public class DownloadFotoPerfilTask extends AsyncTask<String, String, Bitmap> {
	ImageView imageView = null;
	private final WeakReference imageViewReference;
	private MainActivity activity;
	private String selectedId = null;
	Context ctx = null;

	public DownloadFotoPerfilTask(Context ctx, ImageView imageView) {
		// Use a WeakReference to ensure the ImageView can be garbage collected
		imageViewReference = new WeakReference(imageView);
		this.ctx = ctx;
	}

	protected void onPreExecute() {

	}

	protected Bitmap doInBackground(String... params) {
		ApplicationContext appctx = (ApplicationContext) ctx.getApplicationContext();		
		selectedId = params[0];
		Bitmap bitmap = (Bitmap) appctx.getCache().get(selectedId);

		if (bitmap == null) {
			bitmap = HTTPClient.getBitmapFromURL(selectedId);
			if (bitmap != null) {
				appctx.getCache().put(selectedId, bitmap);
			}
		}
	    return bitmap;
	}

	protected void onPostExecute(Bitmap bitmap) {
        if (imageViewReference != null && bitmap != null) {
        	final ImageView imageView = (ImageView) imageViewReference.get();

        	if (imageView != null) {
        		ApplicationContext appctx = (ApplicationContext) ctx.getApplicationContext();
        		List<Persona> listPersonas = appctx.getListPersonas();

        		for (int i = 0; i < listPersonas.size(); i++) {
        			if( listPersonas.get(i).getId().equals(selectedId)) {
        				listPersonas.get(i).setFoto(Tools.bitmapToBase64(bitmap));
        				break;
        			}
				}
        		imageView.setImageBitmap(bitmap);
        	}
        }
    }
}
